<template>
  <div>
    <div v-if="mode === 'DESIGN'">
      <el-time-picker disabled is-range range-separator="至" :start-placeholder="placeholder[0]" :end-placeholder="placeholder[1]" size="default"/>
      <div v-if="showLength" class="length">
        <span>时长：</span>
        <span>{{ timeLength() }}</span>
      </div>
    </div>
    <div v-else-if="mode === 'PC' && !readonly">
      <el-time-picker is-range :value-format="format" v-model="timeRange" @change="changeTime"
        range-separator="至" :start-placeholder="placeholder[0]" :end-placeholder="placeholder[1]" size="default"/>
      <div v-if="showLength" class="length">
        <span>时长：</span>
        <span>{{ timeLength() }}</span>
      </div>
    </div>
    <div v-else-if="mode === 'MOBILE' && !readonly">
      <field right-icon="arrow" readonly clickable name="datetimePicker"
             :model-value="_value ? _value[0] : ''" :placeholder="placeholder[0]" @click="loadTime(0)"/>
      <field right-icon="arrow" readonly clickable name="datetimePicker"
             :model-value="_value ? _value[1] : ''" :placeholder="placeholder[1]" @click="loadTime(1)"/>
      <div v-if="showLength" class="length">
        <span>时长：</span>
        <span>{{ timeLength() }}</span>
      </div>
      <popup v-model:show="showPicker" position="bottom">
        <v-time-picker v-model="timeVal[valIndex]" :formatter="formatter" title="选择时间"
                       :columns-type="columnsType" @confirm="onConfirm" @cancel="showPicker = false"/>
      </popup>
    </div>
    <div v-else>{{ _value[0] }} ~ {{ _value[1] }}</div>
  </div>
</template>

<script>
import {Field, Popup, showFailToast, TimePicker} from 'vant'
import componentMinxins from '/@/views/setting/workflow/components/ComponentMinxins'
const vTimePicker = TimePicker
import moment from 'moment'
import { computed, onMounted, toRefs, reactive } from 'vue'
import { isNotEmpty } from '/@/utils/utils'
const date = '2022-01-01 '

export default {
    name: 'TimeRangePicker',
    mixins: [componentMinxins],
    components: { Field, Popup, vTimePicker },
    props: {
        modelValue: {
            type: Array,
            default: () => {
                return []
            },
        },
        format: {
            type: String,
            default: 'HH:mm:ss',
        },
        placeholder: {
            type: Array,
            default: () => {
                return ['开始时间', '结束时间']
            },
        },
        showLength: {
            type: Boolean,
            default: false,
        },
    },
    emits: ['update:modelValue'], 
    setup(props, context) {
        const { format, modelValue } = toRefs(props)
        const state = reactive({
            showPicker: false,
            valIndex: 0,
            timeRange: null,
            timeVal: [],
        })
        const columnsType = computed(() => {
            const result = []
            if (format.value.indexOf('HH')){
                result.push('hour')
            }else if(format.value.indexOf('mm')){
                result.push('minute')
            }else if(format.value.indexOf('ss')){
                result.push('second')
            }
        })
        const vantType = computed(() => {
            switch (format.value) {
                case 'yyyy':
                    return 'year-month'
                case 'yyyy-MM':
                    return 'year-month'
                case 'yyyy-MM-dd':
                    return 'date'
                case 'yyyy-MM-dd HH':
                    return 'datehour'
                case 'yyyy-MM-dd HH:mm':
                    return 'datetime'
                default:
                    return 'datetime'
            }
        })
        const loadTime = (index) => {
            state.showPicker = true
            state.valIndex = index
            return state.timeVal[index]
        }
        const changeTime = (val) => {
            _value.value = val
        }
        const timeLength = () => {
            //求时长算法
            if (Array.isArray(modelValue.value) && modelValue.value.length > 0) {
                if (modelValue.value[0] === modelValue.value[1]) {
                    return '0 （时长为0，请确认）'
                }
                let start = moment(date + modelValue.value[0])
                let mend = moment(date + modelValue.value[1])
                let hours = mend.diff(start, 'hours')
                let minutes = mend.diff(start, 'minutes')
                let second = mend.diff(start, 'seconds')
                minutes = minutes % 60
                hours = hours % 24
                second = second % 60
                return `${hours > 0 ? hours + '小时 ' : ' '}
                    ${minutes > 0 ? minutes + '分钟 ' : ' '}
                    ${second > 0 ? second + '秒 ' : ' '}`
            } else {
                return '先选择时间哦'
            }
        }
        const onConfirm = (val) => {
            state.showPicker = false
            if (state.valIndex === 1 && _value.value.length === 0) {
                showFailToast('请先选择开始时间')
                return
            }
            _value.value[state.valIndex] = (val.selectedValues || []).join(':')
            if (_value.value[0] && _value.value[1]) {
                if (!moment(date + _value.value[0]).isBefore(moment(date + _value.value[1]))) {
                    _value.value[state.valIndex] = state.valIndex === 0 ? '00:00:00' : _value.value[0]
                    showFailToast('开始时间必须小于结束时间')
                } else {
                    context.emit('update:modelValue', _value.value)
                }
            }
        }
        const formatter = (type, option) => {
            switch (type){
                case 'hour': option.text += ' 时'; break;
                case 'minute': option.text += ' 分'; break;
                case 'second': option.text += ' 秒'; break;
            }
            return option;
        }
        onMounted(() => {
            if (Array.isArray(modelValue.value) && modelValue.value.length > 0) {
                state.timeRange = [
                    isNotEmpty(modelValue.value[0]) ? modelValue.value[0] : '00:00:00',
                    isNotEmpty(modelValue.value[1]) ? modelValue.value[0] : '00:00:00',
                ]
            }
        })
        return {
            ...toRefs(state),
            columnsType,
            vantType,
            loadTime,
            changeTime,
            timeLength,
            onConfirm,
            formatter
        }
    }
}
</script>

<style scoped lang="scss">
.length {
  margin-top: 5px;
}
.length:nth-child(2) {
  color: #8c8c8c;
}
:deep(.el-date-editor--datetimerange .el-input__inner) {
  width: 100%;
  max-width: 400px;
}
:deep(.el-date-editor .el-range-input){
    height: unset;
}
</style>